﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using Common;
using DbControl;
using LiveCharts;
using LiveCharts.Maps;
using LiveCharts.WinForms;
using LiveCharts.Wpf;
using Models;
using GMap;
using GMap.NET;
using GMap.NET.WindowsForms;
using CentralMonitoring.GMap;
using System.Windows.Documents;

namespace CentralMonitoring
{
    public partial class MainFrm : Form
    {
        private lMqttClient mqttClient;
        public static MonitorFrm monitorFrm;
        private int mCount = 6;  //T  暂定  30min/5min=6
        private int mLen = 5;    //T1,T2,T3,T4,T5
        public MainFrm()
        {
            InitializeComponent();
        }

        private void MainFrm_Load(object sender, EventArgs e)
        {
            #region 尺寸比例
            this.WindowState = FormWindowState.Maximized;
            this.panelLeft.Width = this.Width / 4;
            this.panelRight.Width = this.Width / 4;
            int CalHeight = this.Height - this.panelMenu.Height - this.panelReserve.Height;
            this.groupBoxLeftTop.Height = CalHeight / 3;
            this.groupBoxLeftMid.Height = CalHeight / 3;
            this.groupBoxRightTop.Height = CalHeight / 3;
            this.groupBoxRightMiddle.Height = CalHeight / 3;
            this.groupBoxDatas.Height = this.groupBoxleftButtom.Height;
            #endregion
            labelDateTime.Text = DateTime.Now.ToString("时间：yyyy-MM-dd HH:mm:ss");
            OprSql.connectString = ConfigurationManager.AppSettings["consqlstr"].ToString();
            session.mServerIp = ConfigurationManager.AppSettings["serverip"].ToString();
            session.mServerPort = int.Parse(ConfigurationManager.AppSettings["serverport"]);
            session.mClientUUID = ConfigurationManager.AppSettings["clientId"].ToString();
            session.m_currentDeviceId = GetDefaultDevice();
            if (xmlConfig.ReadValue("日志输出").ToString() == "是")
                lLogWrite.isLog = true;
            else
                lLogWrite.isLog = false;

            LoadDeviceList();
            session.mDeviceStatus.DeviceAllNumber = OprUI.GetDeviceCount();
            ShowDeviceNumber();

            ShowChart();
            initDeviceChart();
            initSensorChart();
            initOiChart();
            ShowLasterDatas();
            //ShowLasterAlarms();

            ///////通信
            //mqttClient = new lMqttClient();
            //mqttClient.SensorChanged += MqttClient_SensorChanged;
            //mqttClient.InitMqttServer();
        }
        /// <summary>
        /// 获取默认当前设备
        /// </summary>
        /// <returns></returns>
        private string GetDefaultDevice()
        {
            string DeviceId = "";
            string appset = ConfigurationManager.AppSettings["MdeviceId"];
            if (!string.IsNullOrEmpty(appset))
            {
                DeviceId = appset;
            }
            else
            {
                devices dv = OprDevice.SelectdevicesAll().FirstOrDefault();
                if (dv != null)
                {
                    DeviceId = dv.device_code;
                }
            }
            return DeviceId;
        }
        private delegate void ShowDeviceNumberDelegate();
        private void ShowDeviceNumber()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new ShowDeviceNumberDelegate(ShowDeviceNumber));
            }
            else
            {                              
                this.btnDeviesAll.Text = string.Format("设备数: {0}",session.mDeviceStatus.DeviceAllNumber);
                this.btnDeviceOnline.Text = string.Format("在线数:{0}",session.mDeviceStatus.DeviceOnlineNumber);
                this.btnDeviceOffline.Text = string.Format("离线数：{0}",session.mDeviceStatus.DeviceAllNumber-session.mDeviceStatus.DeviceOnlineNumber);
            }
        }
        private delegate void ShowChartDelegate();
        private void ShowChart()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new ShowChartDelegate(ShowChart));
            }
            else
            {
                initMap();               
                initAlarmChart();              
                initParasChart();
            }
        }
        #region 加载设备信息
        private void LoadDeviceList()
        {
            DataTable dt = OprUI.GetDeevicesForUI();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    Devicelist devicelist = new Devicelist();
                    devicelist.devId = (int)row["id"];
                    devicelist.devCode = row["device_code"].ToString();
                    devicelist.devName = row["device_name"].ToString();
                    devicelist.sensorCode = row["sensor_code"].ToString();
                    devicelist.sensorName = row["sensor_name"].ToString();
                    devicelist.topic = row["sensor_topic"].ToString();
                    if (!(row["oil_name"] is DBNull))
                    {
                        devicelist.oilName = row["oil_name"].ToString();
                    }
                    if (row["online_status"] is DBNull)
                    {
                        devicelist.online_status = false;
                    }
                    else
                    {
                        devicelist.online_status = (int)row["online_status"] > 0 ? true : false;
                        session.mDeviceStatus.DeviceOnlineNumber++;
                    }                    
                    if (row["install_time"] is DateTime)
                    {
                       devicelist.devInstallTime= (DateTime)row["install_time"];                      
                    }
                    if (row["oil_fill_time"] is DateTime)
                    {
                        devicelist.oilFillTime = (DateTime)row["oil_fill_time"];
                    }
                    if (!(row["device_position"] is DBNull))
                    {
                        devicelist.devPos = row["device_position"].ToString();
                    }

                    session.m_dvList.Add(devicelist);

                    //加载算法规则
                    if (!(row["warn_ids"] is DBNull))
                    {
                        DeviceAlgoList algoList = new DeviceAlgoList();
                        algoList.devCode =row["device_code"].ToString();
                        algoList.devName = row["device_name"].ToString();
                        rules rule = OprRules.GetRuleById(int.Parse(row["warn_ids"].ToString()));
                        if(rule != null)
                        {
                            algoList.ppm_uper = decimal.Parse(rule.upper_value);
                            algoList.ppm_upuper = decimal.Parse(rule.upper_upper_value);
                        }
                        session.m_algoList.Add(algoList);

                    }
                }
            }
        }
        #endregion
        #region 数据处理
        private void MqttClient_SensorChanged(object sender, SensorEventArgs e)
        {
            sensordatas vo = e.sensordatas;
            GloabalEvent.SensorPublic(vo);
            Devicelist devicelist = session.m_dvList.Find(t => t.devCode == vo.device_code);
            if (devicelist != null)
            {
                vo.device_name = devicelist.devName;
                vo.sensor_sn = devicelist.sensorCode;
                vo.state = 1;
                OprSensordatas.Insert(vo);
                if (!devicelist.online_status)
                {
                    devicelist.online_status = true;
                    OprSensor.SetOnLineStatue(devicelist.sensorCode,true);
                    session.mDeviceStatus.DeviceOnlineNumber++;
                    ShowDeviceNumber();
                }
                ShowLasterDatas();               
            }
            DeviceAlgoList algolist=session.m_algoList.Find(t=>t.devCode == vo.device_code);
            if(algolist != null)
            {                
                AlgoForWater(vo, algolist);
                lLogWrite.WriteLog(vo.device_name.ToString() +"执行算法:" + vo.aw.ToString()+"：时间" + vo.create_time.ToString());
            }
        }
        /// <summary>
        /// 数据刷新
        /// </summary>
        private delegate void ShowLasterDatasDelegate();
        private void ShowLasterDatas()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new ShowLasterDatasDelegate(ShowLasterDatas));
            }
            else
            {
                try
                {
                    DataTable dt = OprUI.GeLasterDatas();
                    if (dt != null)
                    {
                        this.dataGridView1.DataSource = dt;
                        dataGridView1.RowHeadersVisible = false;
                        dataGridView1.Columns["id"].Visible = false;
                        dataGridView1.Columns["vis40"].Visible = false;                     
                        dataGridView1.Columns["create_time"].HeaderText = "时间";
                        dataGridView1.Columns["create_time"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                        dataGridView1.Columns["create_time"].Width = 140;
                        dataGridView1.Columns["vis"].HeaderText = "粘度";
                        dataGridView1.Columns["temper"].HeaderText = "温度";
                        dataGridView1.Columns["device_name"].HeaderText = "设备名称";
                        dataGridView1.Columns["device_code"].HeaderText = "设备编码";
                        dataGridView1.Columns["sensor_sn"].HeaderText = "终端编码";
                        dataGridView1.Columns["dens"].HeaderText = "密度";
                        dataGridView1.Columns["diel"].HeaderText = "介电常数";
                        dataGridView1.Columns["ppm"].HeaderText = "含水量";
                        dataGridView1.Columns["fe1"].Visible = false;//.HeaderText = "70-90μm(Fe1)";
                        dataGridView1.Columns["fe2"].Visible = false;//.HeaderText = "90-110μm(Fe2)";
                        dataGridView1.Columns["fe3"].Visible = false;//.HeaderText = "110-140μm(Fe3)";
                        dataGridView1.Columns["fe4"].Visible = false;//.HeaderText = "140-170μm(Fe4)";
                        dataGridView1.Columns["fe5"].Visible = false;//.HeaderText = "170-200μm(Fe5)";
                        dataGridView1.Columns["fe6"].Visible = false;//.HeaderText = "200-230μm(Fe6)";
                        dataGridView1.Columns["fe7"].Visible = false;//.HeaderText = "230-280μm(Fe7)";
                        dataGridView1.Columns["fe8"].Visible = false;//.HeaderText = "280-350μm(Fe8)";
                        dataGridView1.Columns["fe9"].Visible = false;//.HeaderText = "350-420μm(Fe9)";
                        dataGridView1.Columns["fe10"].Visible = false;//.HeaderText = ">420μm(Fe10)";
                        dataGridView1.Columns["nfe1"].Visible = false;//.HeaderText = "260-530μm(NFe1)";
                        dataGridView1.Columns["nfe2"].Visible = false;//.HeaderText = "530-1060μm(NFe2)";
                        dataGridView1.Columns["nfe3"].Visible = false;//.HeaderText = "1060-2160μm(NFe3)";
                        dataGridView1.Columns["nfe4"].Visible = false;//.HeaderText = ">2160μm(NFe4)";

                        dataGridView1.ReadOnly = true;
                        dgSetView.SetFormatDataGridView(dataGridView1);
                    }
                }
                catch (Exception ex)
                {
                    lLogWrite.WriteLog("数据查询出错:" + ex.ToString());
                }
            }

        }
        private delegate void ShowLasterAlarmsDelegate();
        private void ShowLasterAlarms()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new ShowLasterAlarmsDelegate(ShowLasterAlarms));
            }
            else
            {
                try
                {
                    DataTable dt = OprUI.GeLasterAlarms();
                    if (dt != null)
                    {
                        this.dataGridView2.DataSource = dt;
                        dataGridView2.RowHeadersVisible = false;
                        dataGridView2.Columns["id"].Visible = false;
                        dataGridView2.Columns["vis40"].Visible = false;
                        dataGridView2.Columns["warn_time"].HeaderText = "时间";
                        dataGridView2.Columns["warn_time"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                        dataGridView2.Columns["warn_time"].Width = 140;
                        dataGridView2.Columns["vis"].Visible = false;//.HeaderText = "粘度";
                        dataGridView2.Columns["aw"].Visible = false;//.HeaderText = "水活性";
                        dataGridView2.Columns["temper"].Visible = false;//.HeaderText = "温度";
                        dataGridView2.Columns["device_name"].HeaderText = "设备名称";
                        dataGridView2.Columns["device_code"].Visible = false;//.HeaderText = "设备编码";
                        dataGridView2.Columns["sensor_sn"].Visible = false;//.HeaderText = "终端编码";
                        dataGridView2.Columns["dens"].Visible = false;//.HeaderText = "密度";
                        dataGridView2.Columns["diel"].Visible = false;// HeaderText = "介电常数";
                        dataGridView2.Columns["ppm"].Visible = false;//.HeaderText = "含水量";
                        dataGridView2.Columns["mo"].Visible = false;//.HeaderText = "70-90μm(Fe1)";
                        dataGridView2.Columns["parameter_code"].HeaderText = "预警项";
                        dataGridView2.Columns["statu"].HeaderText = "预警标志";
                        dataGridView2.Columns["flag"].Visible = false;
                        dataGridView2.Columns["fe"].Visible = false;
                        dataGridView2.Columns["nfe"].Visible = false;
                        dataGridView2.Columns["iso"].Visible = false;
                        dataGridView2.Columns["dens"].Visible = false;
                        dataGridView2.Columns["vis"].Visible = false;
                  

                        dataGridView2.ReadOnly = true;
                        dgSetView.SetFormatDataGridView(dataGridView2);
                    }
                }
                catch (Exception ex)
                {
                    lLogWrite.WriteLog("数据查询出错:" + ex.ToString());
                }
            }
        }
        #endregion
        #region 算法执行
        private void AlgoForWater(sensordatas vo,DeviceAlgoList list)
        {

            if (list.createtimes.Count < mCount)
            {
                list.createtimes.Add(vo.create_time.Value);
                list.wd.Add(vo.temper.Value);
                list.nd.Add(vo.vis.Value);
                list.dens.Add(vo.dens.Value);
                list.Jdcs.Add(vo.diel.Value);
                list.aw.Add(vo.aw.Value);
                list.ppm.Add(vo.ppm.Value);             
            }
            else
            {
                ///均值
                AlgoBufferVo algo_Avg = new AlgoBufferVo();
                algo_Avg.cratetime = list.createtimes.Last();               
                algo_Avg.deviceCode = list.devCode;
                algo_Avg.wd = list.wd.Average();
                algo_Avg.vis = list.nd.Average();
                algo_Avg.dens = list.dens.Average();
                algo_Avg.jdcs = list.Jdcs.Average();
                algo_Avg.aw = list.aw.Average();
                algo_Avg.ppm = list.ppm.Average();
               
                UpdateAvgVo(vo,algo_Avg,list);

                list.createtimes.RemoveAt(0);
                list.createtimes.Add(vo.create_time.Value);
                list.wd.RemoveAt(0);
                list.wd.Add(vo.temper.Value);
                list.nd.RemoveAt(0);
                list.nd.Add(vo.vis.Value);
                list.dens.RemoveAt(0);
                list.dens.Add(vo.dens.Value);
                list.Jdcs.RemoveAt(0);
                list.Jdcs.Add(vo.diel.Value);
                list.aw.RemoveAt(0);
                list.aw.Add(vo.aw.Value);
                list.ppm.RemoveAt(0);
                list.ppm.Add(vo.ppm.Value);
            }

        }
        private bool isAscending(List<decimal> list)
        {
            bool isAscending = true;
            for (int i = 0; i < list.Count - 1; i++)
            {
                if (list[i] > list[i + 1])
                {
                    isAscending = false;
                    break;
                }
            }
            return isAscending;
        }
        private void UpdateAvgVo(sensordatas sen_vo,AlgoBufferVo vo, DeviceAlgoList list)
        {
            if (list.createtimes_Avg.Count < mLen)
            {
                list.createtimes_Avg.Add(vo.cratetime);
                list.wd_Avg.Add(vo.wd);
                list.nd_Avg.Add(vo.vis);
                list.dens_Avg.Add(vo.dens);
                list.Jdcs_Avg.Add(vo.jdcs);
                list.aw_Avg.Add(vo.aw);
                list.ppm_Avg.Add(vo.ppm);
            }
            else
            {
                if (!isAscending(list.wd_Avg))
                {
                    if (isAscending(list.Jdcs_Avg) && isAscending(list.aw_Avg))
                    {
                        if (list.aw_Avg.Last() > list.ppm_upuper)
                        {
                            //alrm
                            warningdatas warnVo = new warningdatas();
                            warnVo.sensor_sn = sen_vo.sensor_sn;
                            warnVo.device_code=sen_vo.device_code;  
                            warnVo.device_name=sen_vo.device_name;
                            warnVo.temper = sen_vo.temper;
                            warnVo.vis=sen_vo.vis;
                            warnVo.dens=sen_vo.dens;
                            warnVo.vis40=sen_vo.vis40;
                            warnVo.diel=sen_vo.diel;
                            warnVo.ppm=sen_vo.ppm;
                            warnVo.mo=sen_vo.mo;
                            warnVo.fe=sen_vo.fe;
                            warnVo.nfe=sen_vo.nfe;
                            warnVo.aw = sen_vo.aw;
                            warnVo.parameter_code = "aw";                           
                            warnVo.warn_time = sen_vo.create_time;
                            warnVo.flag = 1;
                            warnVo.statu = "Red";
                            OprWarndatas.Insert(warnVo);
                            lLogWrite.WriteLog("报警!!!:" + sen_vo.device_name + "报警时间：" +sen_vo.create_time.ToString());
                            ShowLasterAlarms();
                        }
                        else if (list.aw_Avg.Last() > list.ppm_uper)
                        {
                            //warn
                            warningdatas warnVo = new warningdatas();
                            warnVo.sensor_sn = sen_vo.sensor_sn;
                            warnVo.device_code = sen_vo.device_code;
                            warnVo.device_name = sen_vo.device_name;
                            warnVo.temper = sen_vo.temper;
                            warnVo.vis = sen_vo.vis;
                            warnVo.dens = sen_vo.dens;
                            warnVo.vis40 = sen_vo.vis40;
                            warnVo.diel = sen_vo.diel;
                            warnVo.ppm = sen_vo.ppm;
                            warnVo.mo = sen_vo.mo;
                            warnVo.fe = sen_vo.fe;
                            warnVo.nfe = sen_vo.nfe;
                            warnVo.aw = sen_vo.aw;
                            warnVo.parameter_code = "aw";                       
                            warnVo.warn_time = sen_vo.create_time;
                            warnVo.flag = 1;
                            warnVo.statu = "Yellow";
                            OprWarndatas.Insert(warnVo);
                           lLogWrite.WriteLog("预警!:" + sen_vo.device_name + "预警时间：" + sen_vo.create_time.ToString());
                           ShowLasterAlarms();
                        }
                    }
                }
                list.createtimes_Avg.RemoveAt(0);
                list.createtimes_Avg.Add(vo.cratetime);
                list.wd_Avg.RemoveAt(0);
                list.wd_Avg.Add(vo.wd);
                list.nd_Avg.RemoveAt(0);
                list.nd_Avg.Add(vo.vis);
                list.dens_Avg.RemoveAt(0);
                list.dens_Avg.Add(vo.dens);
                list.Jdcs_Avg.RemoveAt(0);
                list.Jdcs_Avg.Add(vo.jdcs);
                list.aw_Avg.RemoveAt(0);
                list.aw_Avg.Add(vo.aw);
                list.ppm_Avg.RemoveAt(0);
                list.ppm_Avg.Add(vo.ppm);
            }
        }
            
            #endregion
            #region 初始化图表
            /// <summary>
            /// 地图初始化
            /// </summary>
            private void initMap()
        {
            //Dictionary<string,string> LanguagePack = new Dictionary<string,string>();
            //LiveCharts.WinForms.GeoMap geoMap1 = new LiveCharts.WinForms.GeoMap();
            //Random r = new Random();
            //Dictionary<string, double> values = new Dictionary<string, double>();
            ////values["MX"] = r.Next(0, 100);
            ////values["CA"] = r.Next(0, 100);
            ////values["US"] = r.Next(0, 100);
            ////values["IN"] = r.Next(0, 100);
            ////values["CN"] = r.Next(0, 100);
            ////values["995"]= values["CN"];
            ////values["JP"] = r.Next(0, 100);
            //geoMap1.HeatMap = values;
            //geoMap1.Source = System.Windows.Forms.Application.StartupPath + "\\" + "World.xml";
            //this.groupBoxMap.Controls.Add(geoMap1);
            //geoMap1.Dock = DockStyle.Fill;
            //geoMap1.LandClick += GeoMap1_LandClick;
            try
            {
                GMapControl gMap = new GMapControl();
                gMap.Manager.Mode = AccessMode.ServerOnly;
                gMap.MapProvider = AMapProvider.Instance; //GMapProviders.GoogleChinaHybridMap;            
                gMap.Position = new PointLatLng(38.33, 108.38);
                gMap.MinZoom = 1;
                gMap.MaxZoom = 18;
                gMap.Zoom = 4.5;
                gMap.ShowCenter = false;
                this.groupBoxMap.Controls.Add(gMap);
                gMap.Dock = DockStyle.Fill;
            }
            catch (Exception ex)
            {
                MessageBox.Show("地图加载错误"+ex.ToString());
            }
            

        }
        private delegate void initDeviceChartDelegate();
        /// <summary>
        /// 设备图表初始化
        /// </summary>
        private void initDeviceChart()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new initDeviceChartDelegate(initDeviceChart));
            }
            else
            {
                carChartDevice.Series.Clear();
                List<string> labels = new List<string>();
                ChartValues<double> values = new ChartValues<double>();

                DataTable dt = OprUI.GetDevicesNumber();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        labels.Add(row["名称"].ToString());
                        values.Add((int)row["数量"]);
                    }
                }
                else
                {
                    labels = new List<string>() { "球磨机", "辊压机", "水泥磨", "高压辊", "风电齿轮箱" };
                    values = new ChartValues<double> { 10, 5, 6, 8, 3 };

                }
                carChartDevice.Series = new LiveCharts.SeriesCollection
                {
                    new ColumnSeries
                    {
                        Title = "设备数",
                        Values=values,    //new ChartValues<int>{ 10,5,6,8,3},
                        DataLabels=true,
                        LabelPoint=point=>point.Y +"台"
                    }
                };
                carChartDevice.AxisX.Add(new Axis
                {
                    //Title="设备数量",
                    Labels = labels,    //new[] { "球磨机", "辊压机", "水泥磨", "高压辊", "风电齿轮箱" },
                    Separator = new Separator
                    {
                        Step = 1,
                        IsEnabled = false
                    },
                    LabelsRotation = 15

                });
                carChartDevice.AxisY.Add(new Axis
                {
                    Title = "设备数量",
                    LabelFormatter = value => value.ToString()
                });
                carChartDevice.DataClick += CarChartDevice_DataClick;
            }
           
        }

        private void CarChartDevice_DataClick(object sender, ChartPoint chartPoint)
        {
            MessageBox.Show("当前选择"+chartPoint.X+","+chartPoint.Y);           
        }

        /// <summary>
        /// 预警图表初始化
        /// </summary>
        private void initAlarmChart()
        {
            #region 单曲线
            //carChartAlarm.Series.Clear();
            //List<string> lables = new List<string> { "温度", "粘度", "密度", "水分", "Fe", "NFe" };
            //Axis axis = new Axis
            //{
            //    Title = "名称",
            //    Labels = lables
            //};
            //ChartValues<double> vales = new ChartValues<double>();
            //for (int i = 0; i < lables.Count; i++)
            //{
            //    vales.Add(30 + i);
            //}
            //carChartAlarm.Series = new SeriesCollection
            //{
            //    new LineSeries
            //    {
            //        Title="运行数",
            //        Values=vales,
            //        Fill=new SolidColorBrush(Colors.Pink),
            //        Stroke=new SolidColorBrush(Colors.Azure),
            //        LineSmoothness=1

            //    }
            //};
            //carChartAlarm.AxisX.Add(axis);
            //carChartAlarm.AxisY.Add(new Axis
            //{
            //    Title = "数量",
            //    LabelFormatter = value => value.ToString()
            //});
            #endregion
            #region 多曲线
            //carChartAlarm.Series.Clear();
            //List<string> titles = new List<string> { "粘度", "水分", "铁磁" };
            //List<ChartValues<double>> _values = new List<ChartValues<double>> 
            //{ 
            //    new ChartValues<double> { 6, 5, 3 },
            //    new ChartValues<double> { 5, 8, 2},
            //    new ChartValues<double> { 3, 4, 1}
            //};
            //List<double> vis_datas = new List<double> { 6, 5, 3 };
            //List<double> mo_datas = new List<double> { 3, 8, 2 };
            //List<double> fe_datas = new List<double> {5,2,6 };
            //List<string> _labels = new List<string>();
            //SeriesCollection seriesViews = new SeriesCollection();
            //for (int i = 0; i < titles.Count; i++)
            //{
            //    LineSeries lineseries = new LineSeries();
            //    lineseries.DataLabels = true;
            //    lineseries.Title = titles[i];
            //    lineseries.Values = _values[i];
            //    lineseries.LineSmoothness = 1;
            //    lineseries.LabelPoint = (point => point.Y + "次");
            //    seriesViews.Add(lineseries);     
            //    _labels.Add(DateTime.Now.AddDays(i-3).ToString("yyyy-MM-dd"));
            //}
            //carChartAlarm.Series = seriesViews;
            //Axis axis = new Axis
            //{
            //    //Title = "名称",
            //    Labels = _labels

            //};
            //carChartAlarm.AxisX.Add(axis);
            //carChartAlarm.AxisY.Add(new Axis
            //{
            //    Title = "预警次数",
            //    LabelFormatter = value => value.ToString()
            //});
            #endregion
            ShowLasterAlarms();

        }
        /// <summary>
        /// 终端图表初始化
        /// </summary>
        private delegate void initSensorChartDelegate();
        private void initSensorChart()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new initSensorChartDelegate(initSensorChart));
            }
            else
            {
                List<string> titles = new List<string>();
                ChartValues<double> values = new ChartValues<double>();
                DataTable dt = OprUI.GetSensorsNumber();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        titles.Add(row["名称"].ToString());
                        values.Add((int)row["数量"]);
                    }
                }
                else
                {
                    titles = new List<string> { "云盒06", "云盒05", "云盒04", "风电" };
                    values = new ChartValues<double> { 10, 50, 30 };

                }
                carChartSensors.Series.Clear();
                carChartSensors.Series = new SeriesCollection
                {
                    new RowSeries
                    {
                        Title="终端数",
                        Values=values,//new ChartValues<double>{ },
                        LabelPoint=point=>point.X+"台",
                        DataLabels=true,
                        Fill=new SolidColorBrush(Colors.IndianRed)
                    }
                };
                Axis axis = new Axis
                {
                    Title = "终端统计",
                    // Labels=titles,                
                    Separator = new Separator()
                    {
                        Step = 10,
                        IsEnabled = true
                    },
                    ShowLabels = false
                };
                carChartSensors.AxisX.Add(axis);
                carChartSensors.AxisY.Add(new Axis
                {
                    //Title = "终端统计",
                    Labels = titles,
                    LabelFormatter = value => value.ToString(),
                    Separator = new Separator()
                    {
                        IsEnabled = false
                    },
                });
            }
        }
        /// <summary>
        /// 油品图表初始化
        /// </summary>
        private delegate void initOilChartDelegate();
        private void initOiChart()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new initOilChartDelegate(initOiChart));
            }
            else
            {
                carChartOils.Series.Clear();
                SeriesCollection seriesCollection = new SeriesCollection();
                LineSeries lineSeries = new LineSeries();
                List<string> labels = new List<string>();
                ChartValues<double> values = new ChartValues<double>();
                DataTable dt = OprUI.GetOilsNumber();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        labels.Add(row["名称"].ToString());
                        values.Add((int)row["数量"]);
                    }
                }
                else
                {
                    labels = new List<string> { "320#", "220#", "150#", "46#" };
                    values = new ChartValues<double> { 5, 6, 10, 2 };

                }
                lineSeries.Title = "油品";
                lineSeries.Values = values;
                lineSeries.DataLabels = true;
                Axis axis = new Axis();
                axis.LabelFormatter = value => value.ToString();
                axis.Labels = labels;
                axis.Separator = new Separator() { IsEnabled = false };
                seriesCollection.Add(lineSeries);
                carChartOils.Series.Clear();
                carChartOils.Series.Add(lineSeries);
                carChartOils.AxisX.Add(axis);
                Axis axis2 = new Axis();
                axis2.Title = "油品统计";
                axis2.Separator.IsEnabled = false;
                axis2.LabelFormatter = value => value.ToString() + "个";
                carChartOils.AxisY.Add(axis2);
            } 
        }
        /// <summary>
        /// 指标参数初始化
        /// </summary>
        private void initParasChart()
        {
            pieChartParas.Series.Clear();          
            List<string> titles = new List<string> { "粘度", "水分","磨粒","清洁度"};
            List<double> values = new List<double> { 10, 40, 30,20 };
            SeriesCollection seriesCollection = new SeriesCollection();
            Func<ChartPoint, string> labelPoint = chartPoint =>
             string.Format("{0} ({1:P})", chartPoint.Y+"台", chartPoint.Participation);
            for (int i = 0; i < titles.Count; i++)
            {
                PieSeries series = new PieSeries();
                series.Title = titles[i];
                series.Values = new ChartValues<double> { values[i] };
                series.DataLabels = true;
                series.LabelPoint = labelPoint;
                seriesCollection.Add(series);
            }
            pieChartParas.Series = seriesCollection;
            pieChartParas.LegendLocation = LegendLocation.Bottom;
        }
        private void GeoMap1_LandClick(object arg1, MapData data)
        {
            MessageBox.Show(data.Id);
        }
        #endregion

        private void labelExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            labelDateTime.Text = DateTime.Now.ToString("时间：yyyy-MM-dd HH:mm:ss");
        }

        #region  菜单
        private void 实时监测ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (monitorFrm == null)
            {
                monitorFrm = new MonitorFrm();
                Devicelist devicelist = session.m_dvList.Find(t => t.devCode == session.m_currentDeviceId);
                if (devicelist == null)
                {
                    Devicelist dev = session.m_dvList.FirstOrDefault();
                    session.m_currentDeviceId = dev.devCode;
                }

            }
            monitorFrm.ReLoadUI(session.m_currentDeviceId);
            monitorFrm.Show();

        }       

        private void 设备信息ToolStripMenuItem8_Click(object sender, EventArgs e)
        {
            DevicesFrm devicesFrm = new DevicesFrm();
            devicesFrm.ShowDialog();
        }

        private void 远程升级ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dlgHardInfoV23 dlg=new dlgHardInfoV23();
            dlg.ShowDialog();
        }

        private void 终端信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SensorsFrm sensorsFrm = new SensorsFrm();
            sensorsFrm.ShowDialog();

        }
        private void 油品管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OilsFrm oilsFrm = new OilsFrm();
            oilsFrm.ShowDialog();
        }
        
        private void 设备配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeviceConfigFrm configFrm=new DeviceConfigFrm();
            configFrm.ShowDialog();

        }
        private void 设备预警ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeviceAlarmConfigFrm alarmConfigFrm = new DeviceAlarmConfigFrm();
            alarmConfigFrm.ShowDialog();
        }

        private void 监测指标ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ParametsFrm parametsFrm = new ParametsFrm();
            parametsFrm.ShowDialog();
        }

        private void 历史数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ViewForm viewForm = new ViewForm();
            viewForm.ShowDialog();
        }
        private void 设备概况ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeviceOverviewFrm viewForm = new DeviceOverviewFrm();
            viewForm.ShowDialog();
        }
        private void 趋势查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ViewChartForm viewChartForm = new ViewChartForm();
            viewChartForm.ShowDialog();
        }
        private void 柱状分析ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChartForm chartForm = new ChartForm();
            if (!string.IsNullOrEmpty(session.m_currentDeviceId))
            {
                devices dev = OprDevice.GetDeviceByDeviceId(session.m_currentDeviceId);
                chartForm.mdeviceName = dev.device_name.ToString();
            }            
            chartForm.ShowDialog();
        }
        private void 预警规则ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeviceByOilParaSet dlg=new DeviceByOilParaSet();
            dlg.ShowDialog();

        }
        private void 预警信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AlarmForm alarmForm = new AlarmForm();
            alarmForm.ShowDialog();
        }

        private void 回放查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //CameraDevice cameraDevice = new CameraDevice();
            //cameraDevice.ShowDialog();

            CameraReplay cameraReplay = new CameraReplay();
            cameraReplay.ShowDialog();
        }
        #endregion

        private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("系统退出工作系统将停止采集备远程监控设备数据，确定要关闭吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
            {
                e.Cancel = true;
            }
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["MdeviceId"].Value = session.m_currentDeviceId;
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
            if (mqttClient != null && mqttClient.isConnected)
            {
                mqttClient.Close();
            }
        }
    }
}
